package com.nnnu.wsnackshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nnnu.wsnackshop.mapper.UsersMapper;
import com.nnnu.wsnackshop.pojo.dto.LoginDTO;
import com.nnnu.wsnackshop.pojo.entity.Users;
import com.nnnu.wsnackshop.service.WechatAuthService;
import com.nnnu.wsnackshop.utils.JwtUtil;
import com.nnnu.wsnackshop.utils.PasswordUtil;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authc.AuthenticationException;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序认证服务实现类
 */
@Service
@RequiredArgsConstructor
public class WechatAuthServiceImpl implements WechatAuthService {
    private final UsersMapper userMapper;

    @Override
    public Map<String, Object> wechatLogin(@NotNull LoginDTO loginDTO) {
        Users user = userMapper.selectOne(
                new LambdaQueryWrapper<Users>().eq(Users::getUsername, loginDTO.getUsername()));
        if (user == null || !PasswordUtil.verify(loginDTO.getPassword(), user.getPassword())) {
            throw new AuthenticationException("用户名或密码错误");
        }

        // 生成 JWT
        String token = JwtUtil.createToken(user.getUsername());

        // 返回token和用户信息
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);

        // 创建用户信息对象（不包含密码）
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("email", user.getEmail());
        userInfo.put("phone", user.getPhone());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("createdAt", user.getCreatedAt());
        userInfo.put("updatedAt", user.getUpdatedAt());

        result.put("userInfo", userInfo);

        return result;
    }
}